<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>授权验证器 - 用户端</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 500px;
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
            text-align: center;
        }

        .subtitle {
            color: #666;
            text-align: center;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .machine-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }

        .machine-info-title {
            font-weight: 600;
            color: #495057;
            margin-bottom: 10px;
            font-size: 14px;
        }

        .machine-id {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #333;
            word-break: break-all;
            background: white;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            font-family: 'Courier New', monospace;
            transition: all 0.3s;
            resize: vertical;
            min-height: 100px;
        }

        textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 14px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        button:active {
            transform: translateY(0);
        }

        .secondary-button {
            background: #6c757d;
            margin-top: 5px;
        }

        .secondary-button:hover {
            box-shadow: 0 10px 20px rgba(108, 117, 125, 0.3);
        }

        .result-box {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            display: none;
        }

        .result-box.show {
            display: block;
            animation: fadeIn 0.5s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .result-success {
            border: 2px solid #28a745;
            background: #d4edda;
        }

        .result-error {
            border: 2px solid #dc3545;
            background: #f8d7da;
        }

        .result-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .result-icon {
            font-size: 24px;
            margin-right: 10px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: auto 1fr;
            gap: 10px;
            margin-top: 15px;
            font-size: 14px;
        }

        .info-label {
            font-weight: 600;
            color: #666;
        }

        .info-value {
            color: #333;
        }

        .copy-button {
            background: #007bff;
            padding: 8px 15px;
            font-size: 14px;
            margin-top: 10px;
        }

        .system-info {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #dee2e6;
        }

        .system-info-title {
            font-weight: 600;
            color: #495057;
            margin-bottom: 10px;
            font-size: 14px;
        }

        .system-info-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            font-size: 13px;
        }

        .system-info-label {
            color: #666;
        }

        .system-info-value {
            color: #333;
            font-weight: 500;
        }
        
        /* 服务器连接状态样式 */
        .server-connection {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .server-connected {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        
        .server-disconnected {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .connection-settings {
            margin-top: 10px;
            display: none;
        }
        
        .connection-settings.show {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔓 授权验证器</h1>
        <p class="subtitle">验证您的授权码 <span style="opacity: 0.7; font-style: italic;">by Chaxi</span></p>

        <div class="machine-info">
            <div class="machine-info-title">📟 您的机器标识</div>
            <div class="machine-id" id="machineId">正在获取...</div>
            <button class="copy-button" onclick="copyMachineId()">📋 复制机器ID</button>
        </div>

        <div class="form-group">
            <label for="licenseKey">授权码</label>
            <textarea id="licenseKey" placeholder="请输入您的授权码..."></textarea>
            <div style="display: flex; margin-top: 5px; gap: 5px;">
                <button onclick="copyTextFromTextarea()" style="flex: 1; padding: 6px; font-size: 12px; background: #6c757d;">📋 复制内容</button>
                <button onclick="pasteToTextarea()" style="flex: 1; padding: 6px; font-size: 12px; background: #6c757d;">📋 粘贴内容</button>
                <button onclick="clearTextarea()" style="flex: 1; padding: 6px; font-size: 12px; background: #dc3545;">🗑️ 清空</button>
            </div>
        </div>

        <button onclick="verifyLicense()">🔍 验证授权</button>
        <button onclick="loadFromFile()" class="secondary-button">📁 从文件加载</button>
        <button onclick="revokeLicense()" class="secondary-button" style="background: #dc3545;">❌ 注销授权</button>

        <div id="resultBox" class="result-box">
            <!-- 验证结果将显示在这里 -->
        </div>

        <div class="system-info">
            <div class="system-info-title">💻 系统信息</div>
            <div id="systemInfo">
                <!-- 系统信息将显示在这里 -->
            </div>
            
            <!-- 服务器连接部分 -->
            <div style="margin-top: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div class="system-info-title">🌐 服务器连接</div>
                    <button id="toggleConnectionBtn" onclick="toggleConnectionSettings()" style="padding: 5px 10px; font-size: 12px; width: auto; margin: 0;">
                        ⚙️ 设置
                    </button>
                </div>
                
                <div id="serverConnection" class="server-connection server-disconnected">
                    <span id="connectionStatus">未连接到授权服务器</span>
                    <button id="connectBtn" onclick="toggleServerConnection()" style="padding: 5px 10px; font-size: 12px; width: auto; margin: 0;">
                        连接
                    </button>
                </div>
                
                <div id="connectionSettings" class="connection-settings">
                    <div class="form-group" style="margin-bottom: 10px;">
                        <label for="serverUrl" style="font-size: 12px; margin-bottom: 5px;">服务器地址</label>
                        <input type="text" id="serverUrl" placeholder="http://localhost:3000" style="width: 100%; padding: 8px; border-radius: 5px; border: 1px solid #ddd;">
                    </div>
                    <div style="display: flex; gap: 5px;">
                        <button onclick="saveConnectionSettings()" style="flex: 1; padding: 6px; font-size: 12px; background: #28a745;">保存设置</button>
                        <button onclick="toggleConnectionSettings()" style="flex: 1; padding: 6px; font-size: 12px; background: #6c757d;">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { ipcRenderer } = require('electron');
        let currentMachineId = '';
        let currentSystemInfo = null;

        // 页面加载时获取系统信息和已保存的授权
        window.addEventListener('DOMContentLoaded', async () => {
            await loadSystemInfo();
            await loadSavedLicense();
            
            // 添加右键菜单支持 (现代Electron方式)
            const textarea = document.getElementById('licenseKey');
            textarea.addEventListener('contextmenu', function(e) {
                e.preventDefault();
                ipcRenderer.send('show-context-menu', 'textarea');
            });
            
            // 为所有输入框添加右键菜单
            document.querySelectorAll('input, textarea').forEach(input => {
                input.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    ipcRenderer.send('show-context-menu', 'input');
                });
            });
            
            // 为其他元素添加右键菜单
            document.addEventListener('contextmenu', function(e) {
                if (!e.target.closest('input, textarea')) {
                    e.preventDefault();
                    ipcRenderer.send('show-context-menu', 'general');
                }
            });
        });
        
        // 加载已保存的授权信息
        async function loadSavedLicense() {
            try {
                const savedLicense = localStorage.getItem('savedLicense');
                if (savedLicense) {
                    const licenseData = JSON.parse(savedLicense);
                    // 自动填充授权码
                    document.getElementById('licenseKey').value = licenseData.licenseKey || '';
                    // 如果保存了验证结果，显示它
                    if (licenseData.verificationResult) {
                        displayResult(licenseData.verificationResult);
                    }
                }
            } catch (error) {
                console.error('加载保存的授权失败:', error);
            }
        }

        async function loadSystemInfo() {
            try {
                // 获取系统信息
                currentSystemInfo = await ipcRenderer.invoke('get-system-info');
                currentMachineId = currentSystemInfo.hash;
                
                // 显示机器ID
                document.getElementById('machineId').textContent = currentMachineId;
                
                // 显示系统信息 - 访问raw属性中的信息
                const rawInfo = currentSystemInfo.raw || {};
                const systemInfoHtml = `
                    <div class="system-info-item">
                        <span class="system-info-label">操作系统:</span>
                        <span class="system-info-value">${rawInfo.platform || '未知'}</span>
                    </div>
                    <div class="system-info-item">
                        <span class="system-info-label">系统版本:</span>
                        <span class="system-info-value">${rawInfo.release || '未知'}</span>
                    </div>
                    <div class="system-info-item">
                        <span class="system-info-label">处理器:</span>
                        <span class="system-info-value">${rawInfo.cpuModel || '未知'}</span>
                    </div>
                    <div class="system-info-item">
                        <span class="system-info-label">内存:</span>
                        <span class="system-info-value">${rawInfo.totalMemory ? Math.round(rawInfo.totalMemory / 1024 / 1024 / 1024) + ' GB' : '未知'}</span>
                    </div>
                    <div class="system-info-item">
                        <span class="system-info-label">主机名:</span>
                        <span class="system-info-value">${rawInfo.hostname || '未知'}</span>
                    </div>
                `;
                document.getElementById('systemInfo').innerHTML = systemInfoHtml;
            } catch (error) {
                console.error('获取系统信息失败:', error);
                document.getElementById('machineId').textContent = '获取失败';
            }
        }

        function copyMachineId() {
            if (!currentMachineId) {
                alert('机器ID尚未获取');
                return;
            }
            
            navigator.clipboard.writeText(currentMachineId).then(() => {
                alert('机器ID已复制到剪贴板！\n请将此ID提供给管理员生成授权码。');
            });
        }

        async function verifyLicense() {
            // 获取授权码并清理
            let licenseKey = document.getElementById('licenseKey').value;
            
            if (!licenseKey) {
                alert('请输入授权码！');
                return;
            }
            
            if (!currentMachineId) {
                alert('系统信息尚未加载，请稍后再试');
                return;
            }
            
            // 清理授权码（移除所有空格、换行和制表符）
            licenseKey = licenseKey.replace(/[\s\n\r\t]/g, '');
            console.log('清理后授权码长度:', licenseKey.length);
            console.log('清理后授权码前50个字符:', licenseKey.substring(0, 50));
            
            // 调用主进程验证授权
            const result = await ipcRenderer.invoke('verify-license', licenseKey, currentMachineId);
            
            if (result.success) {
                // 保存授权信息到localStorage
                try {
                    localStorage.setItem('savedLicense', JSON.stringify({
                        licenseKey: licenseKey,
                        verificationResult: result.data,
                        lastVerified: new Date().toISOString()
                    }));
                    console.log('授权信息已保存到本地存储');
                } catch (error) {
                    console.error('保存授权信息失败:', error);
                }
                
                displayResult(result.data);
            } else {
                displayError(result.error);
            }
        }

        function displayResult(data) {
            const resultBox = document.getElementById('resultBox');
            
            if (data.valid) {
                // 验证成功
                resultBox.className = 'result-box result-success show';
                
                // 安全地获取日期（增加异常处理）
                let expiryDateStr = '未知';
                let issueDateStr = '未知';
                
                try {
                    if (data.licenseInfo.expiryDate) {
                        const expiryDate = new Date(data.licenseInfo.expiryDate);
                        expiryDateStr = expiryDate.toLocaleString('zh-CN');
                    }
                    
                    if (data.licenseInfo.issueDate) {
                        const issueDate = new Date(data.licenseInfo.issueDate);
                        issueDateStr = issueDate.toLocaleString('zh-CN');
                    }
                } catch (error) {
                    console.error('日期格式化错误:', error);
                }
                
                // 安全地提取功能列表
                const featuresStr = Array.isArray(data.features) ? data.features.join(', ') : '基础功能';
                
                // 安全地获取授权类型
                const licenseType = data.licenseInfo.type ? data.licenseInfo.type.toUpperCase() : '标准';
                
                // 安全地获取剩余时间
                const remainingTime = data.remainingTime && data.remainingTime.formatted ? 
                    data.remainingTime.formatted : '未知';
                
                resultBox.innerHTML = `
                    <div class="result-title">
                        <span class="result-icon">✅</span>
                        授权验证成功！
                    </div>
                    
                    <div class="info-grid">
                        <span class="info-label">授权ID:</span>
                        <span class="info-value">${data.licenseInfo.id || '未知'}</span>
                        
                        <span class="info-label">授权类型:</span>
                        <span class="info-value">${licenseType}</span>
                        
                        <span class="info-label">生成时间:</span>
                        <span class="info-value">${issueDateStr}</span>
                        
                        <span class="info-label">过期时间:</span>
                        <span class="info-value">${expiryDateStr}</span>
                        
                        <span class="info-label">剩余时间:</span>
                        <span class="info-value">${remainingTime}</span>
                        
                        <span class="info-label">功能权限:</span>
                        <span class="info-value">${featuresStr}</span>
                    </div>
                    
                    <button onclick="launchProgram()" style="margin-top: 20px;">
                        🚀 启动受保护的程序
                    </button>
                `;
            } else {
                // 验证失败
                resultBox.className = 'result-box result-error show';
                resultBox.innerHTML = `
                    <div class="result-title">
                        <span class="result-icon">❌</span>
                        授权验证失败
                    </div>
                    <p style="color: #721c24; margin-top: 10px;">
                        ${data.message || '授权码无效或已过期'}
                    </p>
                    <p style="color: #666; margin-top: 10px; font-size: 14px;">
                        原因: ${data.reason || '未知错误'}
                    </p>
                `;
            }
        }

        function displayError(error) {
            const resultBox = document.getElementById('resultBox');
            resultBox.className = 'result-box result-error show';
            resultBox.innerHTML = `
                <div class="result-title">
                    <span class="result-icon">⚠️</span>
                    验证出错
                </div>
                <p style="color: #721c24; margin-top: 10px;">
                    ${error}
                </p>
            `;
        }

        async function loadFromFile() {
            const result = await ipcRenderer.invoke('load-license');
            
            if (result.success) {
                document.getElementById('licenseKey').value = result.licenseKey;
                alert('授权码已从文件加载！');
            }
        }

        async function launchProgram() {
            const licenseKey = document.getElementById('licenseKey').value.trim();
            await ipcRenderer.invoke('launch-program', licenseKey);
        }
        
        // 注销授权
        function revokeLicense() {
            if (confirm('确定要注销当前授权吗？这将清除所有授权信息。')) {
                try {
                    // 清除本地存储的授权信息
                    localStorage.removeItem('savedLicense');
                    
                    // 清空输入框
                    document.getElementById('licenseKey').value = '';
                    
                    // 隐藏结果框
                    document.getElementById('resultBox').classList.remove('show');
                    
                    alert('授权已成功注销！');
                } catch (error) {
                    console.error('注销授权失败:', error);
                    alert('注销授权失败: ' + error.message);
                }
            }
        }
        
        // 复制文本区域的内容到剪贴板
        function copyTextFromTextarea() {
            const textarea = document.getElementById('licenseKey');
            const text = textarea.value;
            
            if (!text) {
                alert('文本区域为空，没有内容可复制');
                return;
            }
            
            navigator.clipboard.writeText(text).then(() => {
                alert('内容已复制到剪贴板！');
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败: ' + err);
                
                // 备用方法
                textarea.select();
                document.execCommand('copy');
            });
        }
        
        // 从剪贴板粘贴内容到文本区域
        function pasteToTextarea() {
            const textarea = document.getElementById('licenseKey');
            
            navigator.clipboard.readText().then(text => {
                textarea.value = text;
                alert('内容已从剪贴板粘贴！');
            }).catch(err => {
                console.error('粘贴失败:', err);
                alert('粘贴失败: ' + err + '\n\n请尝试使用右键菜单或键盘快捷键(Ctrl+V)粘贴');
                
                // 提示用户使用键盘快捷键
                textarea.focus();
            });
        }
        
        // 清空文本区域
        function clearTextarea() {
            const textarea = document.getElementById('licenseKey');
            textarea.value = '';
        }
        
        // ========== 服务器连接相关函数 ==========
        let serverSocket = null;
        let isConnected = false;
        let reconnectInterval = null;
        
        // 在页面加载时加载服务器设置
        window.addEventListener('DOMContentLoaded', () => {
            loadServerSettings();
        });
        
        // 加载保存的服务器设置
        function loadServerSettings() {
            try {
                const serverSettings = localStorage.getItem('serverSettings');
                if (serverSettings) {
                    const settings = JSON.parse(serverSettings);
                    document.getElementById('serverUrl').value = settings.url || '';
                    
                    // 如果设置了自动连接，则连接服务器
                    if (settings.autoConnect) {
                        connectToServer(settings.url);
                    }
                }
            } catch (error) {
                console.error('加载服务器设置失败:', error);
            }
        }
        
        // 切换连接设置面板显示
        function toggleConnectionSettings() {
            const settingsPanel = document.getElementById('connectionSettings');
            settingsPanel.classList.toggle('show');
            
            const btn = document.getElementById('toggleConnectionBtn');
            if (settingsPanel.classList.contains('show')) {
                btn.textContent = '❌ 关闭';
            } else {
                btn.textContent = '⚙️ 设置';
            }
        }
        
        // 保存连接设置
        function saveConnectionSettings() {
            const serverUrl = document.getElementById('serverUrl').value.trim();
            
            if (!serverUrl) {
                alert('请输入服务器地址');
                return;
            }
            
            try {
                // 验证URL格式
                new URL(serverUrl);
                
                // 保存设置
                localStorage.setItem('serverSettings', JSON.stringify({
                    url: serverUrl,
                    lastSaved: new Date().toISOString(),
                    autoConnect: false
                }));
                
                alert('服务器设置已保存');
                toggleConnectionSettings(); // 关闭设置面板
            } catch (error) {
                alert('无效的服务器地址，请输入完整URL（例如：http://localhost:3000）');
            }
        }
        
        // 切换服务器连接状态
        function toggleServerConnection() {
            if (isConnected) {
                disconnectFromServer();
            } else {
                const serverUrl = document.getElementById('serverUrl').value.trim();
                if (!serverUrl) {
                    alert('请先设置服务器地址');
                    toggleConnectionSettings(); // 打开设置面板
                    return;
                }
                
                connectToServer(serverUrl);
            }
        }
        
        // 连接到服务器
        function connectToServer(url) {
            try {
                if (serverSocket) {
                    serverSocket.close();
                }
                
                // 更新UI为连接中状态
                const connectionStatus = document.getElementById('connectionStatus');
                const connectBtn = document.getElementById('connectBtn');
                const connectionBox = document.getElementById('serverConnection');
                
                connectionStatus.textContent = '正在连接...';
                connectBtn.disabled = true;
                
                // 将WebSocket URL转换为WebSocket协议
                const wsUrl = url.replace(/^http/, 'ws');
                console.log(`正在连接到服务器: ${wsUrl}`);
                
                // 创建WebSocket连接
                serverSocket = new WebSocket(`${wsUrl}/ws`);
                
                serverSocket.onopen = () => {
                    console.log('已连接到服务器');
                    isConnected = true;
                    connectionStatus.textContent = '已连接到授权服务器';
                    connectBtn.textContent = '断开';
                    connectBtn.disabled = false;
                    connectionBox.className = 'server-connection server-connected';
                    
                    // 注册客户端
                    registerClient();
                    
                    // 清除可能存在的重连定时器
                    if (reconnectInterval) {
                        clearInterval(reconnectInterval);
                        reconnectInterval = null;
                    }
                    
                    // 设置自动重连
                    serverSocket.onclose = () => {
                        handleDisconnection();
                    };
                };
                
                serverSocket.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    handleDisconnection();
                };
                
                serverSocket.onmessage = (event) => {
                    handleServerMessage(event.data);
                };
                
            } catch (error) {
                console.error('连接服务器失败:', error);
                handleDisconnection();
            }
        }
        
        // 处理服务器断开连接
        function handleDisconnection() {
            console.log('与服务器的连接已断开');
            isConnected = false;
            
            const connectionStatus = document.getElementById('connectionStatus');
            const connectBtn = document.getElementById('connectBtn');
            const connectionBox = document.getElementById('serverConnection');
            
            connectionStatus.textContent = '未连接到授权服务器';
            connectBtn.textContent = '连接';
            connectBtn.disabled = false;
            connectionBox.className = 'server-connection server-disconnected';
            
            // 设置自动重连（每30秒尝试一次）
            if (!reconnectInterval) {
                reconnectInterval = setInterval(() => {
                    if (!isConnected) {
                        const serverUrl = document.getElementById('serverUrl').value.trim();
                        if (serverUrl) {
                            console.log('尝试重新连接服务器...');
                            connectToServer(serverUrl);
                        }
                    } else {
                        clearInterval(reconnectInterval);
                        reconnectInterval = null;
                    }
                }, 30000);
            }
        }
        
        // 断开服务器连接
        function disconnectFromServer() {
            if (serverSocket) {
                serverSocket.close();
                serverSocket = null;
            }
            
            isConnected = false;
            const connectionStatus = document.getElementById('connectionStatus');
            const connectBtn = document.getElementById('connectBtn');
            const connectionBox = document.getElementById('serverConnection');
            
            connectionStatus.textContent = '未连接到授权服务器';
            connectBtn.textContent = '连接';
            connectionBox.className = 'server-connection server-disconnected';
            
            // 清除重连定时器
            if (reconnectInterval) {
                clearInterval(reconnectInterval);
                reconnectInterval = null;
            }
        }
        
        // 向服务器注册客户端
        function registerClient() {
            if (!serverSocket || serverSocket.readyState !== WebSocket.OPEN) {
                return;
            }
            
            try {
                // 获取当前授权信息
                let licenseInfo = null;
                try {
                    const savedLicense = localStorage.getItem('savedLicense');
                    if (savedLicense) {
                        const licenseData = JSON.parse(savedLicense);
                        if (licenseData.verificationResult && licenseData.verificationResult.licenseInfo) {
                            licenseInfo = licenseData.verificationResult.licenseInfo;
                        }
                    }
                } catch (error) {
                    console.error('获取授权信息失败:', error);
                }
                
                // 发送注册消息
                const registrationMessage = {
                    type: 'register',
                    machineId: currentMachineId,
                    systemInfo: currentSystemInfo ? currentSystemInfo.raw : null,
                    licenseInfo: licenseInfo,
                    timestamp: Date.now()
                };
                
                serverSocket.send(JSON.stringify(registrationMessage));
                console.log('已向服务器注册客户端');
                
                // 设置心跳包（每30秒发送一次）
                setInterval(() => {
                    if (serverSocket && serverSocket.readyState === WebSocket.OPEN) {
                        const heartbeatMessage = {
                            type: 'heartbeat',
                            machineId: currentMachineId,
                            timestamp: Date.now()
                        };
                        serverSocket.send(JSON.stringify(heartbeatMessage));
                    }
                }, 30000);
                
            } catch (error) {
                console.error('注册客户端失败:', error);
            }
        }
        
        // 处理服务器消息
        function handleServerMessage(message) {
            try {
                const data = JSON.parse(message);
                console.log('收到服务器消息:', data.type);
                
                switch (data.type) {
                    case 'welcome':
                        console.log('服务器欢迎消息:', data.message);
                        break;
                        
                    case 'revoke_license':
                        // 服务器要求撤销授权
                        if (data.machineId === currentMachineId) {
                            handleRemoteRevocation(data);
                        }
                        break;
                        
                    case 'license_updated':
                        // 授权信息已更新
                        if (data.machineId === currentMachineId) {
                            alert('您的授权信息已被管理员更新，请重新验证授权。');
                            // 可以选择自动重新验证
                        }
                        break;
                }
                
            } catch (error) {
                console.error('处理服务器消息失败:', error);
            }
        }
        
        // 处理远程撤销授权
        function handleRemoteRevocation(data) {
            try {
                alert(`您的授权已被管理员远程撤销。\n原因: ${data.reason || '未提供'}`);
                
                // 清除本地存储的授权信息
                localStorage.removeItem('savedLicense');
                
                // 清空输入框
                document.getElementById('licenseKey').value = '';
                
                // 隐藏结果框
                document.getElementById('resultBox').classList.remove('show');
                
                // 发送确认消息
                if (serverSocket && serverSocket.readyState === WebSocket.OPEN) {
                    const confirmationMessage = {
                        type: 'revocation_confirmation',
                        machineId: currentMachineId,
                        licenseId: data.licenseId,
                        timestamp: Date.now()
                    };
                    serverSocket.send(JSON.stringify(confirmationMessage));
                }
                
            } catch (error) {
                console.error('处理远程撤销失败:', error);
            }
        }
    </script>
</body>
</html>
